package ee.reliability.tool.ui.window;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

@SuppressWarnings("serial")
public class ExcelFileChooser extends JFileChooser {

	public ExcelFileChooser() {
//		super("D:\\Users\\Ilja\\Downloads\\Attachments_2012_11_7");
		setAcceptAllFileFilterUsed(false);
		addChoosableFileFilter(new ExcelFileFilter());
		setMultiSelectionEnabled(true);
	}

	public ArrayList<Workbook> getSelectedFilesAsWorkbook() {

		try {
			ArrayList<Workbook> wbList = new ArrayList<>();
			for (File file : getSelectedFiles()) {
				InputStream fis = new FileInputStream(file);
				wbList.add(WorkbookFactory.create(fis));
			}
			return wbList;
		} catch (InvalidFormatException | IOException e) {
			throw new RuntimeException("Can't open file!");
		}
	}
	private static class ExcelFileFilter extends FileFilter{
		@Override
		public String getDescription() {
			return "Excell WorkBook";
		}

		@Override
		public boolean accept(File f) {
			return f.isDirectory() ? true :
				f.getName().matches(".*\\.xlsx?$");// .xls or .xlsx in the end of file name
		}
	}

}
